package com.gxuwz.bignews.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.gxuwz.bignews.R;
import com.gxuwz.bignews.model.db.NewsHistoryDao;
import com.gxuwz.bignews.model.entity.NewsHistory;
import com.gxuwz.bignews.view.activity.NewsDetailActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HistoryFragment extends Fragment {
    private RecyclerView rvHistory;
    private TextView tvEmpty;
    private HistoryAdapter adapter;
    private List<NewsHistory> historyList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_history, container, false);
        rvHistory = view.findViewById(R.id.rv_history);
        tvEmpty = view.findViewById(R.id.tv_empty);
        // 隐藏底部导航栏
        if (getActivity() != null) {
            android.view.View nav = getActivity().findViewById(R.id.nav_view);
            if (nav != null) nav.setVisibility(View.GONE);
        }
        // 返回按钮
        android.widget.ImageButton btnBack = view.findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> {
            // 显示底部导航栏
            if (getActivity() != null) {
                android.view.View nav = getActivity().findViewById(R.id.nav_view);
                if (nav != null) nav.setVisibility(View.VISIBLE);
                // 返回个人中心
                getParentFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new UserCenterFragment())
                        .commit();
            }
        });
        rvHistory.setLayoutManager(new LinearLayoutManager(getContext()));
        // 获取当前用户手机号
        SharedPreferences sp = requireContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        String phone = sp.getString("phone", "");
        // 查询历史记录
        historyList = new NewsHistoryDao(requireContext()).getAllHistoryByPhone(phone);
        adapter = new HistoryAdapter(historyList);
        rvHistory.setAdapter(adapter);
        // 空历史提示
        if (historyList == null || historyList.isEmpty()) {
            tvEmpty.setVisibility(View.VISIBLE);
            rvHistory.setVisibility(View.GONE);
        } else {
            tvEmpty.setVisibility(View.GONE);
            rvHistory.setVisibility(View.VISIBLE);
        }
        return view;
    }

    // 历史记录适配器
    class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder> {
        private final List<NewsHistory> list;
        HistoryAdapter(List<NewsHistory> list) { this.list = list; }
        @NonNull
        @Override
        public HistoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
            return new HistoryViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull HistoryViewHolder holder, int position) {
            NewsHistory history = list.get(position);
            holder.tvTitle.setText(history.getTitle());
            holder.tvDate.setText(formatTime(history.getTime()));
            holder.tvSource.setText(history.getPhone()); // 可替换为其他信息
            if (history.getThumbnailPic() != null && !history.getThumbnailPic().isEmpty()) {
                Glide.with(holder.ivThumb.getContext())
                        .load(history.getThumbnailPic())
                        .placeholder(R.drawable.ic_launcher_background)
                        .error(R.drawable.ic_launcher_background)
                        .into(holder.ivThumb);
                holder.ivThumb.setVisibility(View.VISIBLE);
            } else {
                holder.ivThumb.setImageResource(R.drawable.ic_launcher_background);
                holder.ivThumb.setVisibility(View.INVISIBLE);
            }
            // 点击跳转详情
            holder.itemView.setOnClickListener(v -> {
                Intent intent = new Intent(getContext(), NewsDetailActivity.class);
                intent.putExtra("uniquekey", history.getUniquekey());
                startActivity(intent);
            });
        }
        @Override
        public int getItemCount() { return list.size(); }
        class HistoryViewHolder extends RecyclerView.ViewHolder {
            TextView tvTitle, tvDate, tvSource;
            android.widget.ImageView ivThumb;
            HistoryViewHolder(@NonNull View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_news_title);
                tvDate = itemView.findViewById(R.id.tv_news_date);
                tvSource = itemView.findViewById(R.id.tv_news_source);
                ivThumb = itemView.findViewById(R.id.iv_news_thumb);
            }
        }
        // 时间戳格式化
        private String formatTime(long time) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            return sdf.format(new Date(time));
        }
    }
}